package com.et.machine.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.et.drive.out.IOutGoodsImpl
import com.et.drive.out.OutGoodsParam
import com.et.logger.ELog
import com.et.logger.TAGS
import com.et.machine.BuildConfig
import com.et.machine.IMachineAidl
import com.et.machine.convert.OutGoodsStatusEnum
import com.et.util.toByteArray

class OutService : Service() {

    override fun onCreate() {
        super.onCreate()
        ELog.d(TAGS.machine, "machine:out service onCreate")
        Intent(this, StableService::class.java).apply {
            ELog.d(TAGS.machine, "machine:start stable service")
            startService(this)
        }
    }

    override fun onBind(intent: Intent): IBinder {
        ELog.d(TAGS.machine, "machine:out service onBind")
        return holder
    }

    override fun onRebind(intent: Intent?) {
        super.onRebind(intent)
        Intent(this, StableService::class.java).apply {
            ELog.d(TAGS.machine, "machine:stable service onRebind")
            startService(this)
        }
    }

    override fun onUnbind(intent: Intent?): Boolean {
        return true
    }

    class Holder : IMachineAidl.Stub() {

        override fun outGoods(box: Int, channel: Int, cent: Int, pay: Int, serial: Int): Boolean {
            ELog.d(
                TAGS.machine,
                "OutGoods Request:[box,$box],[channel,$channel],[priceCent,$cent],[pay,${
                    pay.toString(16)
                }]"
            )
            val p = OutGoodsParam()
            when (BuildConfig.FLAVOR) {
                "et" -> {
                    val serialByteArray = serial.toByteArray(3)
                    val data = byteArrayOf(
                        0, 0,
                        box.toByte(), 1, channel.toByte(),
                        cent.shr(16).toByte(),
                        cent.shr(8).toByte(),
                        cent.toByte(), pay.toByte(),
                        serialByteArray[0], serialByteArray[1], serialByteArray[2],
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                        0
                    )
                    p.byteArray = data
                }
                "dc" -> {

                }
                "fs" -> {
                }
            }
            val num = IOutGoodsImpl.outGoods(p)
            if (num == OutGoodsStatusEnum.SUCCESS) return true else {
                ELog.d(TAGS.machine, "Out Send Fault:$num")
            }
            return false
        }
    }

    companion object {
        const val ACTION = "com.et.action.out" // Don't allow changed
        val holder = Holder()
    }
}